import { store } from '@/store'
import { setToken } from '@/store/global'
import { message } from 'antd'
import Axios from 'axios'

const axios = Axios.create({
  //添加代理解决跨域问题
  baseURL: process.env.REACT_APP_BASE_URL,
  //设置超时时间
  timeout: 8000,
})

//请求拦截器（发送之前）
const { token } = store.getState().global
axios.interceptors.request.use(
  config => {
    if (token) {
      config.headers!.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    error(error.message)
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(
  response => {
    if (response.data.code === 401) {
      if (token) {
        message.error('登录过期,请重新登录')
      }
      store.dispatch(setToken(''))
    } else if (response.data.code !== 200) {
      message.error(response.data.message)
      return Promise.reject(response.data)
    }
    return response
  },
  err => {
    if (err.message === 'Network Error') {
      message.error('网络错误,请检查您的网络是否正常')
    } else if (err.message.includes('timeout')) {
      message.error('请求超时，请稍后重试')
    }
    // 添加其它异常处理
    return Promise.reject(err)
  }
)
export default axios
